import com.google.gson.Gson;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: yuanjianpeng
 * Date: 2018/10/17
 * Project: httpclient
 * Version: 1.0
 * Description:
 */
public class HttpClientApp {

    private static final String url = "https://api.sms.jpush.cn/v1/messages/batch";

    private static final String appKey = "050da99bfd642e2bac82596b";

    private static final String secret = "ed3df684102fc91ced1b4b51";

    public static void main(String[] args) throws IOException {

        HttpClient httpclient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);

        String authorization = Base64.encodeBase64String((appKey+":"+secret).getBytes("utf-8"));

        httpPost.setHeader("Authorization", "Basic "+authorization);

        Map<String,Object> content = new HashMap<>();
        content.put("content","10.32.7.6磁盘区间不足");
        List<Map<String,Object>> recipients = new ArrayList<>();
        Map<String,Object> recipient = new HashMap<>();
        recipient.put("mobile","15313270380");
        recipient.put("temp_para",content);
        recipients.add(recipient);

        JGSMSReq jgsmsReq = new JGSMSReq();
        jgsmsReq.setTemp_id("155607");
        jgsmsReq.setRecipients(recipients);
        Gson gson = new Gson();
        String request =  gson.toJson(jgsmsReq);

        StringEntity stringEntity = new StringEntity(request,"application/json","utf-8"); //APPLICATION_JSON
        httpPost.setEntity(stringEntity);

        HttpResponse response = httpclient.execute(httpPost);

        //4.获取响应对象中的响应码
        StatusLine statusLine = response.getStatusLine();//获取请求对象中的响应行对象
        int responseCode = statusLine.getStatusCode();//从状态行中获取状态码
        if (responseCode == 200) {
            //5.  可以接收和发送消息
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity,"utf-8");

            //6.从消息载体对象中获取操作的读取流对象
//            InputStream input = entity.getContent();
//            BufferedReader br = new BufferedReader(new InputStreamReader(input));
//            String str1 = br.readLine();
//            String result = new String(str1.getBytes("gbk"), "utf-8");

            System.out.println("服务器的响应是:" + result);
//            br.close();
//            input.close();
        } else {
            System.out.println("响应失败!");
        }
    }
}
